package com.mysiteforme.admin.controller.common;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.mysiteforme.admin.entity.ExcelImport;
import com.mysiteforme.admin.util.ExcelUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/excel")
public class ImportExcelController{

    @PostMapping(value = "/readExcel")
    public Object readExcel(MultipartFile file){
        //接收导入数组
        List<ExcelImport> excelImportList = null;
        try {
            excelImportList = ExcelImportUtil.importExcel(file.getInputStream(), ExcelImport.class, new ImportParams());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return excelImportList;
    }

    /**
     * excel 下载
     *
     * @param response response只能使用一次
     */
    @GetMapping(value = "/excelExport")
    public void exportExcel(HttpServletResponse response) {
        //mock 下载导出测试数据
        ExcelImport export1 = new ExcelImport("测试1", "CN", new Date());
        ExcelImport export2 = new ExcelImport("测试2", "EN", new Date());
        List<ExcelImport> list = new ArrayList<>();
        list.add(export1);
        list.add(export2);

        //参数配置
        ExportParams params = new ExportParams();
        //此处设置ExcelType HSSF为excel2003版本，XSSF为excel2007版本
        params.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, ExcelImport.class, list);
        ExcelUtils.downloadExcel(response, workbook, "excel-export");
    }

}
